<template></template>
<script lang="ts">
import * as THREE from 'three';
import { CSS2DRenderer, OrbitControls, CSS2DObject } from 'three/examples/jsm/Addons.js';

// 场景与相机
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 0, 5);

// 渲染器
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

// CSS2D 渲染器
const labelRenderer = new CSS2DRenderer();
labelRenderer.setSize(window.innerWidth, window.innerHeight);
labelRenderer.domElement.style.position = 'absolute';
labelRenderer.domElement.style.top = '0';
labelRenderer.domElement.style.pointerEvents = 'none';
document.body.appendChild(labelRenderer.domElement);



// 立方体
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshNormalMaterial();
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

// 边框高亮
const edges = new THREE.EdgesGeometry(geometry);
const line = new THREE.LineSegments(edges, new THREE.LineBasicMaterial({ color: 0xffff00 }));
cube.add(line);
line.visible = false;

// 标签
const labelDiv = document.createElement('div');
labelDiv.className = 'label';
labelDiv.textContent = '立方体';
const label = new CSS2DObject(labelDiv);
label.position.set(0, 1.2, 0);
cube.add(label);

// Raycaster 检测
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
let selected: THREE.Object3D | null = null;

function onMouseMove(event: MouseEvent) {
  mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

  raycaster.setFromCamera(mouse, camera);
  const intersects = raycaster.intersectObjects([cube]);

  if (intersects.length > 0) {
    line.visible = true;
    document.body.style.cursor = 'pointer';
    selected = intersects[0].object;
  } else {
    line.visible = false;
    document.body.style.cursor = 'default';
    selected = null;
  }
}

// OrbitControls
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;

function onClick() {
  if (selected) {
    alert('点击了立方体');
  }
}

// 事件监听
window.addEventListener('mousemove', onMouseMove);
window.addEventListener('click', onClick);

// 动画循环
function animate() {
  requestAnimationFrame(animate);
  cube.rotation.y += 0.01;
  controls.update();
  renderer.render(scene, camera);
  labelRenderer.render(scene, camera);
}
animate();

// 自适应
window.addEventListener('resize', () => {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
  labelRenderer.setSize(window.innerWidth, window.innerHeight);
});

</script>